'use strict';

var getIpFromHosts = require('./getIpFromHosts.js');
var HttpServer = require('./HttpServer.js');

var cfg = {
	"lookup": {
		// "hostname_redis": "redis.host",
		// "hostname_mysql": "mysql.host",
		// "www.google.com": "test.host",
		"NODE_ENV": "test.env"
	},
	"mysql": {
		"host": process.env.hostname_mysql || 'localhost',
		"port": 3306,
		"user": 'root',
		"database": 'o2o',
		"password": 'mysql'
	},
	"redis": {
		"host": process.env.hostname_redis || "127.0.0.1",
		"port": "6379"
	},
	"test": {
		"host": "127.0.0.1",
		"env": "aaa"
	},
	"http": {
		"port": 5001
	}
};

function __setupEnv() {
	console.log(' [x] setupEnv');
	var count = 0;
	var replaceCnt = 0;
	var keys = Object.keys(cfg.lookup);
	var len = keys.length;

	function next(fulfil) {
		// console.log(' [x] next count=%d', count);
		if (count === keys.length) {
			// TODO
			fulfil();
			return;
		} else {
			var key = keys[count];
			__setUpOneKey(key)

			.then(function(isOk) {
				console.log(' [x] set up %s done', key);
				count += 1;
				replaceCnt += isOk;
				next(fulfil);
			});
		}
	}


	return new Promise(function(fulfil, reject) {
		next(fulfil);
	});
}

function __setUpOneKey(key) {
	return new Promise(function(fulfil, reject) {
		// console.log(" [x] lookup %s", key);
		if (process.env[key]) {
			console.log(" [x] found %s in process.env , value = %s", key, process.env[key]);
			var path = cfg.lookup[key].split('.');
			__replaceCfgValue(path, process.env[key]);
			fulfil(1);

		} else {
			getIpFromHosts.getIp2(key)

			.then(function(res) {
				if (res.ip) {
					console.log(" [x] found %s = %s , in /etc/hosts ", key, res.ip);
					__replaceCfgValue(cfg.lookup[key].split('.'), res.ip);
					fulfil(1);
				} else {
					console.log(" [x] not found  %s", key);
					fulfil(0);
				}
			});
		}
	});
}

function __replaceCfgValue(path, value) {
	console.log(' [x] __replaceCfgValue [%s]=%s', path.join('.'), value);
	var target = cfg;
	var last = path.length - 1;
	for (var i = 0; i < last; i++) {
		target = target[path[i]];
	}
	var key = path[last];
	target[key] = value;
}


__setupEnv()

.then(function() {
	console.log(' [x] setupEnv done');
	delete cfg.lookup;
	console.log('-----------------env-----------');
	console.log(cfg);
	console.log('-----------------env-----------');


	var httpServer = new HttpServer(cfg);
	httpServer.go();
});